<?php
/**
 * Created by PhpStorm.
 * User: lzh 9157374
 * Date: 2018/5/21
 * Time: 下午1:53
 */
namespace Core\common;

class Take
{
    /**
     * 接管模块操作
     * @param $name
     * @param $arguments
     * @param array $config
     */
    public function yStart($name, $arguments,$config = [])
    {
        $module = $this->_getCurrentModule($name,$config);

        $config['module'] = $module;
        $config = $this->_mergeSetConfig($config);
        Assist::globalVal('yWe7',$config);

        $do = Request::params('do') == 'index'?'index/index':Request::params('do');
        $controller = explode("/",$do);
        $do = $controller[0];
        $op = $controller[1];
        try{
            $class = '\\'.$module.'\\controller\\'.$do;
            if(class_exists($class)){
                $classObj = new $class();
                if(method_exists($classObj,$op)){
                    $classObj->$op($arguments);
                }else{
                    exit('操作:'.$op.'不存在');
                }
            }else{
                exit(''.$class.'类不存在');
            }
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }


    /**
     * 合并配置
     * @param $config
     * @return array
     */
    private function _mergeSetConfig($config)
    {
        $_default = [
            'static'   => 'static',//静态资源文件夹
            'view_dir' => 'view',//视图文件夹
            'html_suffix' => '.html',//html后缀
        ];

        return array_merge($_default,$config);
    }

    /**
     * 获取处理模块
     * @param $name
     * @param $config
     * @return mixed|string
     */
    private function _getCurrentModule($name,$config)
    {

        $module = '';
        if($config['module']){
            if(!is_array($config['module'])){
                return $config['module'];
            }
            if(strpos(strtolower($name),'doweb') === 0){
                $module = $config['module']['web']?$config['module']['web']:$config['module'][0];
            }
            if(strpos(strtolower($name),'domobile') === 0){
                $module = $config['module']['mobile']?$config['module']['mobile']:$config['module'][1];
            }
            if(strpos(strtolower($name),'dopage') === 0){
                $module = $config['module']['page']?$config['module']['page']:$config['module'][1];
            }
        }


        if(empty($module)){
            if(strpos(strtolower($name),'doweb') === 0){
                $module = 'admin';
            }elseif(strpos(strtolower($name),'domobile') === 0){
                $module = 'mobile';
            }elseif(strpos(strtolower($name),'dopage') === 0){
                $module = 'app';
            }
        }

        if(empty($module)){
            exit('请为当前请求指定处理模块');
        }

        return $module;
    }
}